import React, { useState, useRef } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  TreeSelect,
  DatePicker,
  Radio,
  Checkbox,
  TimePicker,
} from 'antd';
import './index.less';

import IrrButton from '@/components/IrrButton';

import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

export interface IotFormDataItem {
  renderType?: string; // 表单渲染类型
  title: string; //表单标签
  dataIndex?: string; // 表单Key值
  disabled?: boolean; //是否禁用
  required?: boolean; //是否必填
  render?: Function; //自定义渲染
  extra?: anyObject; //表单额外属性
  dataSource?: any; //选择组件 数据源
  validator?: string; //输入框校验类型 phone-手机号 ｜ email-邮箱 ｜ idCard-身份证 ｜ int-正整数 ｜ noSpecial无特殊字符 ｜ blank空格 ｜ letterOrNum/数字或字母 | _int/整数包括0
  formItemProps?: any; //自定义formItem属性
  isShow?: boolean; //是否显示当前条目
  customSelectOption?: {
    buttonOption?: {
      text?: string;
      onClick?: Function; //点击打开弹窗
      label?: string;
    };
    isInputShow?: boolean;
  }; //自定义选择配置项
  list?: IotFormDataItem[]; // 表单分组
  children?: any;
  multiple?: boolean;
  format?: string;
  formatTime?: string;
  MultiSelect?: boolean; // 是否多选
  everyItemStyle?: any;
  itemClass?: any;
}

interface Props {
  children?: any;
  className?: string;
  layout?: string;
  formOption?: anyObject;
  currentRecord?: anyObject;
  onValuesChange?: Function;
  contentFormStyle?: anyObject;
  totolItemProps?: anyObject;
  formDisabled?: boolean;
  searchList: IotFormDataItem[];
  resetTrans?: Function;
  onSearchSubmit?: Function;
  queryAndReset?: {
    queryText?: string;
    resetText?: string;
    queryVisible?: boolean;
    resetVisible?: boolean;
    style?: any;
    className?: string;
  };
}
const IrrSearchForm = (props: Props) => {
  const irrFormRef = useRef<any>(null);
  const [resetFlag, setResetFlag] = useState<boolean>(true);

  const {
    className = '',
    resetTrans = () => {},
    layout = 'horizontal',
    formOption = {},
    children,
    contentFormStyle = {},
    totolItemProps = { minWidth: '250px' },
    searchList = [],
    queryAndReset = {
      queryText: '查询',
      resetText: '重置',
      queryVisible: true,
      resetVisible: true,
      style: {},
      className: '',
    },
  } = props;

  const renderFormItem = (item: any, index: number) => {
    const { formDisabled = false } = props;
    const {
      extra = {
        maxLength: 30,
      },
      required = false,
      MultiSelect = false,
      disabled = formDisabled,
      dataSource = [],
      dataIndex,
      title,
      titleStr,
      formatTime,
      renderType,
      formItemProps,
    } = item;
    const formItemExtra: any = {
      label: title,
      name: dataIndex,
      className: 'iot-form-item',
      ...formItemProps,
    };
    if (item.render) {
      return item.render();
    }
    if (renderType === 'input') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
          getValueFromEvent={(event) => {
            let value = event.target.value;
            if (extra && Object.keys(extra).length > 0) {
              if (extra.type === 'number') {
                value = value.slice(0, extra.maxLength);
              }
            }
            return value;
          }}
        >
          <Input
            placeholder={`请输入${titleStr || title}`}
            disabled={disabled}
            {...extra}
          />
        </Form.Item>
      );
    } else if (renderType === 'select') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Select
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            optionFilterProp="label"
            showSearch={dataSource?.length > 8}
            allowClear={required ? false : true}
            {...extra}
          >
            {dataSource.map((it: any) => {
              return (
                <Option key={it.value} value={it.value} disabled={it.disabled}>
                  {it.label}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
      );
    } else if (renderType === 'treeSelect') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <TreeSelect
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            treeDefaultExpandAll
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={dataSource}
            multiple={MultiSelect}
            disabled={disabled}
            allowClear={required ? false : true}
            {...extra}
          />
        </Form.Item>
      );
    } else if (renderType === 'datePicker') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <DatePicker
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            disabledDate={disabledDate}
            {...extra}
            allowClear={required ? false : true}
          />
        </Form.Item>
      );
    } else if (renderType === 'RangePicker') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <RangePicker
            style={{ width: '100%' }}
            // placeholder={['开始时间'，'结束']}
            disabled={disabled}
            disabledDate={disabledDate}
            onChange={handleRangePicker}
            defaultValue={item.defaultValue}
            {...extra}
            allowClear={false}
          />
        </Form.Item>
      );
    } else if (renderType === 'timePicker') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <TimePicker
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            {...extra}
            format={formatTime}
            allowClear={required ? false : true}
          />
        </Form.Item>
      );
    } else if (renderType === 'radio') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Radio.Group disabled={disabled}>
            {dataSource.map((item: any, index: number) => {
              return (
                <Radio
                  disabled={item.disabled}
                  value={item.value}
                  key={index.toString()}
                  {...extra}
                >
                  {item.label}
                </Radio>
              );
            })}
          </Radio.Group>
        </Form.Item>
      );
    } else if (renderType === 'checkbox') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Checkbox.Group disabled={disabled}>
            <div className="checkbox-group">
              <div className="checkbox-list">
                {dataSource.map((item: any, index: number) => {
                  return (
                    <Checkbox
                      className="checkbox-item"
                      key={index}
                      value={item.value}
                    >
                      {item.label}
                    </Checkbox>
                  );
                })}
              </div>
            </div>
          </Checkbox.Group>
        </Form.Item>
      );
    }
  };
  const disabledDate = (current: any) => {
    return current && current >= moment().endOf('day');
  };

  const restBtnStatus = () => {
    return resetFlag;
  };

  const handleRangePicker = (time: any, dateString: Array<string>) => {
    // setStartTime(time[0]);
    // setEndTime(time[1]);
  };

  const resetForm = () => {
    setResetFlag(true);
    irrFormRef.current?.resetFields();
  };

  const onFormSubmit = (val: any) => {
    const { onSearchSubmit } = props;
    onSearchSubmit && onSearchSubmit(val);
  };
  const curValuesChange = (curVal: any, totolVal: any, changeType?: string) => {
    const curFlag = [];
    for (let i in totolVal) {
      if (totolVal[i] === 0) {
        curFlag.push(i);
      } else if (totolVal[i]) {
        curFlag.push(i);
      }
    }
    setResetFlag(curFlag.length === 0);
    const { onValuesChange } = props;
    onValuesChange && onValuesChange(curVal, totolVal, changeType);
  };

  return (
    <>
      <Form
        name="temp_search_top__form"
        ref={irrFormRef}
        onFinish={onFormSubmit}
        className={
          className ? `search_top__form ${className}` : `search_top__form`
        }
        autoComplete="off"
        colon={false}
        //@ts-ignore
        onValuesChange={curValuesChange}
        //@ts-ignore
        layout={layout}
        {...formOption}
      >
        <div className="search_top_form__containter">
          <div className="search_top_form__content" style={contentFormStyle}>
            {searchList.map((formItem, index) => {
              const {
                isShow = true,
                everyItemStyle = {},
                itemClass = '',
              } = formItem;
              return isShow ? (
                <div
                  key={index.toString()}
                  style={{ ...totolItemProps, ...everyItemStyle }}
                  className={`form_content__item form_content__item__${index} ${itemClass}`}
                >
                  {renderFormItem(formItem, index)}
                </div>
              ) : null;
            })}
          </div>
          <div className="extra">{children}</div>
        </div>
        <div
          style={queryAndReset.style}
          className={`search_form__btns ${queryAndReset.className}`}
        >
          {queryAndReset.queryVisible ? (
            <div className="search_form--query">
              <Button type="primary" htmlType="submit">
                {queryAndReset.queryText}
              </Button>
            </div>
          ) : null}
          {queryAndReset.resetVisible ? (
            <div className="search_form--reset">
              <IrrButton
                disabled={restBtnStatus()}
                onClick={() => {
                  resetForm();
                  resetTrans && resetTrans();
                }}
              >
                {queryAndReset.resetText}
              </IrrButton>
            </div>
          ) : null}
        </div>
      </Form>
    </>
  );
};

export default IrrSearchForm;
